package com.sa.token.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sa.token.dto.request.user.DelUserRequest;
import com.sa.token.dto.request.user.UserPageRequest;
import com.sa.token.dto.response.user.AuthorityResponse;
import com.sa.token.dto.response.user.UserButtonResponse;
import com.sa.token.dto.response.user.UserMenuResponse;
import com.sa.token.dto.response.user.UserResponse;
import com.sa.token.entity.SysUserEntity;
import com.sa.token.mapper.SysUserMapper;
import com.sa.token.mapper.SysUserRoleMapper;
import com.sa.token.message.Result;
import com.sa.token.message.StandardResponse;
import com.sa.token.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author xhs
 * @since 2021-08-27
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {
    @Autowired
    private BaseServiceImpl baseService;
    @Resource
    private SysUserMapper userMapper;
    @Resource
    private SysUserRoleMapper userRoleMapper;

    /**
     * 分页查询用户信息
     *
     * @param userPageRequest
     * @return
     */
    @Override
    public StandardResponse queryUser(UserPageRequest userPageRequest) {
        Page<UserResponse> page = new Page<>(userPageRequest.getCurrent(), userPageRequest.getSize());
        Page<UserResponse> userResponsePage = userMapper.queryUser(page, userPageRequest.getUserName(), userPageRequest.getLoginId());
        return StandardResponse.build(Result.QUERY_SUCCESS).setData(userResponsePage);
    }

    /**
     * 删除用户
     *
     * @param delUserRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public StandardResponse delUser(DelUserRequest delUserRequest) {
        SysUserEntity sysUser = baseService.getSysUserEntity(delUserRequest.getLoginId());
        if (sysUser == null) {
            return StandardResponse.build(Result.USER_NOT_EXIST);
        }
        // 删除用户
        sysUser.setDelFlg("1");
        sysUser.setUpdater(StpUtil.getLoginIdAsString());
        getBaseMapper().updateById(sysUser);
        return StandardResponse.build(Result.DEl_SUCCESS);
    }

    /**
     * 冻结账号
     *
     * @param delUserRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public StandardResponse frozenAccount(DelUserRequest delUserRequest) {
        SysUserEntity sysUser = baseService.getSysUserEntity(delUserRequest.getLoginId());
        if (sysUser == null) {
            return StandardResponse.build(Result.USER_NOT_EXIST);
        }
        // 冻结账号
        sysUser.setUserStatus("1");
        sysUser.setUpdater(StpUtil.getLoginIdAsString());
        getBaseMapper().updateById(sysUser);
        return StandardResponse.build(Result.FROZEN_ACCOUNT);
    }

    /**
     * 解冻账号
     *
     * @param delUserRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public StandardResponse thawAccount(DelUserRequest delUserRequest) {
        SysUserEntity sysUser = baseService.getSysUserEntity(delUserRequest.getLoginId());
        if (sysUser == null) {
            return StandardResponse.build(Result.USER_NOT_EXIST);
        }
        // 解冻账号
        sysUser.setUserStatus("0");
        sysUser.setUpdater(StpUtil.getLoginIdAsString());
        getBaseMapper().updateById(sysUser);
        return StandardResponse.build(Result.THAW_ACCOUNT);
    }

    /**
     * 根据登录账号查询权限
     *
     * @return
     */
    @Override
    public StandardResponse getUserAuthority() {
        String loginId = StpUtil.getLoginIdAsString();
        List<UserMenuResponse> userMenu = userRoleMapper.getUserMenu(loginId);
        List<UserButtonResponse> userButton = userRoleMapper.getUserButton(loginId);
        // 存放树结构的数据
        List<UserMenuResponse> ampCompanyTreeList = new ArrayList<>();
        if (userMenu.size() > 0 && userMenu != null) {
            // 找到所有的一级节点存放在一个list中
            List<UserMenuResponse> parntList = new ArrayList<>();
            for (UserMenuResponse pList : userMenu) {
                // 父节点的pID为 0，
                if ("0".equals(pList.getParentId())) {
                    parntList.add(pList);
                }
            }
            // 为一级节点设置子节点 ,getChildren采用递归算法
            for (UserMenuResponse amp : parntList) {
                UserMenuResponse companyResponse = new UserMenuResponse();
                companyResponse = amp;
                companyResponse.setChildren(getChildren(amp.getMenuId(), userMenu));
                ampCompanyTreeList.add(amp);
            }
        }

        AuthorityResponse response = new AuthorityResponse();
        response.setUserMenuList(ampCompanyTreeList);
        response.setUserButtonList(userButton);
        return StandardResponse.build(Result.QUERY_SUCCESS).setData(response);
    }

    /**
     * 递归组装树节点数据
     *
     * @param id   父节点id
     * @param list 所有数据
     * @return
     */
    public List<UserMenuResponse> getChildren(String id, List<UserMenuResponse> list) {
        List<UserMenuResponse> childrenList = new ArrayList<>();
        // 子节点
        for (UserMenuResponse children : list) {
            if (id.equals(children.getParentId())) {
                childrenList.add(children);
            }
        }
        // 把子节点的子节点循环一遍
        for (UserMenuResponse cList : childrenList) {
            cList.setChildren(getChildren(cList.getMenuId(), list));
        }
        return childrenList;
    }
}
